package com.asiainfo.indb.view;

import com.asiainfo.indb.control.LogService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author zym
 * @date 2019-10-19 11:49
 */
public class LogPanel extends JDialog implements WindowListener {

    public static final String CRLF = "\r\n";

    private JTextArea textArea;

    private LogService service;

    private AtomicLong lineNum = new AtomicLong(1);

    /**
     * 需要当前日志面板所依赖的服务实现联动
     *
     * @param service 服务
     */
    public LogPanel(LogService service) {
        this.service = service;

        // 提交log的页面渲染
        EventQueue.invokeLater(() -> {
            renderDialog();
            renderTextArea();
        });
    }

    /**
     * 渲染对话框
     */
    private void renderDialog() {
        // 居中
        setSize(InDbConfig.LOG_WIDTH, InDbConfig.LOG_HEIGHT);
        Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        setLocation(center.x - getWidth() / 2, center.y - getHeight() / 2);

        setModal(true);
        setAlwaysOnTop(true);
        setTitle("入库日志");
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(this);
    }

    private void renderTextArea() {
        // 渲染日志区域
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel panel = new JPanel(new BorderLayout());
        this.textArea = new JTextArea();
        this.textArea.setLineWrap(true);
        this.textArea.setEditable(false);

        panel.add(this.textArea, BorderLayout.CENTER);
        scrollPane.setViewportView(panel);

        setContentPane(scrollPane);
        setVisible(true);
    }

    /**
     * 确认当前面板是否就绪
     *
     * @return true or false
     */
    public boolean ready() {
        return this.textArea != null;
    }

    /**
     * 追加日志显示
     *
     * @param msg 日志信息
     */
    public void append(String msg) {
        textArea.append("[" + lineNum.getAndIncrement() + "] -> ");
        textArea.append(msg);
        textArea.append(CRLF);
    }

    @Override
    public void windowOpened(WindowEvent e) {

    }

    @Override
    public void windowClosing(WindowEvent e) {

    }

    @Override
    public void windowClosed(WindowEvent e) {
        this.service.dispose();
    }

    @Override
    public void windowIconified(WindowEvent e) {

    }

    @Override
    public void windowDeiconified(WindowEvent e) {

    }

    @Override
    public void windowActivated(WindowEvent e) {

    }

    @Override
    public void windowDeactivated(WindowEvent e) {

    }
}
